import {HttpUtil} from "../../utils/http.util";
import {Injectable} from "@angular/core";
import {Storage} from '@ionic/storage';
import { Events } from 'ionic-angular';
import {RESULT_CODE} from "../../utils/contansts";
import {Response} from '../../model/response';

/**
 * Created by longcwan on 2017/4/10.
 */

@Injectable()
export class LoginService{
  constructor(private httpUtil: HttpUtil ,private storage: Storage,private events: Events){}
  login(url: string,username: string,password: string){
    let params = new URLSearchParams();
    params.set("username",username);
    params.set("password",password);
     this.httpUtil.get(url,params).subscribe((data: Response<any>) => {
      if(RESULT_CODE.RESULT_SUCCESS == data.code){
        this.storage.ready().then(() => {
          // set a key/value
          this.storage.set('username', username);
          this.storage.set('password', password);
          this.events.publish('user:login:success', username);
        });
      }else{
        this.events.publish('user:login:error', data.message);
      }

    }, err => {
       this.events.publish('user:login:error', err);
    });
  }
}
